﻿// ===============================================================================
// Project Name        :	Weisenz.Core
// Project Description :	Weisenz系统核心类库。
// ===============================================================================
// Class Name          :	CacheKey
// Class Version       :	v1.0.0.0
// Class Description   :	系统应用程序缓存处理类，无法继承此类。
// Author              :	Charles
// Create Time         :	2012/3/29 
// Update Time         :	2012/3/29 
// ===============================================================================
// Copyright © Weisenz 2012 . All rights reserved.
// ===============================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;

namespace Weisenz.Core
{
    /// <summary>
    /// 系统应用程序缓存处理类，无法继承此类。
    /// </summary>
    public sealed class Cache
    {

        /// <summary>
        /// 从系统缓存中检索指定的缓存对象。
        /// </summary>
        /// <param name="key">要检索的缓存项的标识符。</param>
        /// <returns>检索到的缓存项，未找到该键时为 null。</returns>
        public static object GetCache(string key)
        {
            System.Web.Caching.Cache cache = HttpContext.Current.Cache;
            return cache.Get(key);
        }

        /// <summary>
        /// 检索缓存中的缓存对象枚举数。
        /// </summary>
        /// <returns>返回缓存对象枚举数。</returns>
        public static IDictionaryEnumerator GetEnumerator()
        {
            System.Web.Caching.Cache cache = HttpContext.Current.Cache;
            return cache.GetEnumerator();
        }

        /// <summary>
        /// 向缓存中插入对象。
        /// </summary>
        /// <param name="key">缓存项的标识符。</param>
        /// <param name="obj">要插入缓存中的对象。</param>
        public static void Insert(string key, object obj)
        {
            System.Web.Caching.Cache cache = HttpRuntime.Cache;
            cache.Insert(key, obj);
        }

        /// <summary>
        /// 向缓存中插入具有过期时间和时间间隔的对象。
        /// </summary>
        /// <param name="key">缓存键值。</param>
        /// <param name="obj">要插入缓存中的对象。</param>
        /// <param name="absoluteExpiration">缓存的绝对过期时间。</param>
        /// <param name="timespan">最后一次访问所插入对象时与该对象过期时之间的时间间隔</param>
        public static void Insert(string key, object obj, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache cache = HttpRuntime.Cache;
            cache.Insert(key, obj, null, absoluteExpiration, slidingExpiration);
        }

        /// <summary>
        /// 从应用程序缓存中清除指定键值的对象。
        /// </summary>
        public static object Remove(string key)
        {
            System.Web.Caching.Cache cache = HttpContext.Current.Cache;
            return cache.Remove(key);
        }

        /// <summary>
        /// 从应用程序缓存中清除所有对象。
        /// </summary>
        public static void Clear()
        {
            System.Web.Caching.Cache cache = HttpContext.Current.Cache;
            IDictionaryEnumerator cacheEnumerator = cache.GetEnumerator();
            while (cacheEnumerator.MoveNext())
            {
                cache.Remove(cacheEnumerator.Key.ToString());
            }
        }

        /// <summary>
        /// 初始化系统语言包。
        /// </summary>
        private static Dictionary<string, string> InitLanguage()
        {
            string path = Path.Combine(Config.Path, "Common/Language.xml");
            Dictionary<string, string> cacheObj = new Dictionary<string, string>();
            if (File.Exists(path))
            {
                XmlTextReader reader = new XmlTextReader(path);
                while (reader.Read())
                {
                    if (reader.Name == "item")
                    {
                        string key = reader.GetAttribute("key");
                        string value = reader.GetAttribute("value");
                        if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                        {
                            cacheObj.Add(key, value);
                        }
                    }
                }
                reader.Close();
            }
            return cacheObj;
        }

        /// <summary>
        /// 获取系统语言缓存。
        /// </summary>
        /// <param name="key">键</param>
        public static string GetLanguage(string key)
        {
            string str = string.Empty;
            Dictionary<string, string> lanCache = (Dictionary<string, string>)GetCache(CacheFields.Languages);
            if (lanCache == null)
            {
                lanCache = InitLanguage();
                Insert(CacheFields.Languages, lanCache);
            }
            if (!string.IsNullOrEmpty(key))
            {
                str = lanCache.TryGetValue(key, out str) ? str : string.Empty;
            }
            return str;
        }

        /// <summary>
        /// 初始化应用程序URL重写缓存。
        /// </summary>
        private static Dictionary<string, string> InitRewrite()
        {
            XmlTextReader reader = new XmlTextReader(Path.Combine(Config.Path, "Common/Rewrite.xml"));
            Dictionary<string, string> cacheObj = new Dictionary<string, string>();
            string attribute = string.Empty;
            for (string rewriteUrl = string.Empty; reader.Read(); rewriteUrl = string.Empty)
            {
                if (reader.Name == "rule")
                {
                    attribute = reader.GetAttribute("look");
                    rewriteUrl = reader.GetAttribute("to");
                    if (!string.IsNullOrEmpty(attribute) && !string.IsNullOrEmpty(attribute))
                    {
                        attribute = string.Format("{0}{1}", Config.Path, attribute);
                        rewriteUrl = string.Format("{0}{1}", Config.Path, rewriteUrl);
                        cacheObj.Add(attribute, rewriteUrl);
                    }
                }
                attribute = string.Empty;
            }
            reader.Close();
            return cacheObj;
        }

        /// <summary>
        /// 获取指定URL重写后的路径。
        /// </summary>
        /// <param name="strVal">当前URL。</param>
        /// <returns>返回重写重写后的路径。</returns>
        public static string GetUrl(string strVal)
        {
            Dictionary<string, string> urlCache = (Dictionary<string, string>)GetCache(CacheFields.Url);
            if (urlCache == null)
            {
                urlCache = InitRewrite();
                Insert(CacheFields.Url, urlCache);
            }
            if (urlCache.Count > 0)
            {
                foreach (KeyValuePair<string, string> pair in urlCache)
                {
                    if (!string.IsNullOrEmpty(strVal) && !string.IsNullOrEmpty(pair.Key))
                    {
                        if (Regex.IsMatch(strVal, pair.Key, RegexOptions.IgnoreCase))
                        {
                            return Regex.Replace(strVal, pair.Key, pair.Value, RegexOptions.IgnoreCase);
                        }
                    }
                }
            }
            return string.Empty;
        }
    }
}
